package cn.ai.shoes.client.service.impl;

import cn.ai.shoes.client.entity.OssUploadLog;
import cn.ai.shoes.client.entity.vo.OssUploadLogPageVo;
import cn.ai.shoes.client.entity.vo.OssUploadLogVo;
import cn.ai.shoes.client.mapper.OssUploadMapper;
import cn.ai.shoes.client.service.OssUploadService;
import cn.ai.shoes.client.service.ComfyuiService;
import cn.ai.shoes.client.service.OssUploadLogService;
import cn.ai.shoes.common.core.mybatis.LambdaQueryWrapperX;
import cn.ai.shoes.common.exception.ServiceException;
import cn.ai.shoes.common.exception.constant.GlobalErrorCodeConstants;
import cn.ai.shoes.common.pojo.entity.CommonResult;
import cn.ai.shoes.core.pojo.entity.MyUser;
import cn.ai.shoes.core.utils.AliyunOssUtils;
import cn.ai.shoes.core.utils.SecurityUtils;
import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import jakarta.annotation.Resource;
import jodd.util.StringUtil;
import lombok.extern.slf4j.Slf4j;
import org.jetbrains.annotations.NotNull;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.InputStream;
import java.util.Arrays;
import java.util.Map;

@Slf4j
@Service
public class OssUploadServiceImpl implements OssUploadService {
    // 允许上传的格式 图片形式
    private static final String[] IMAGE_TYPE = new String[]{".bmp", ".jpg", ".jpeg", ".png"};
    private static final String USERS_FILE_PAHT = "users/";
    public static final String CLIPSPACE = "clipspace";


    @Resource
    private AliyunOssUtils aliyunOssUtils;
    @Resource
    private ComfyuiService comfyuiService;
    @Resource
    private OssUploadLogService ossUploadLogService;


    /**
     * 上传图片到OSS并生成日志（multipart版）
     * @param multipart 图片文件
     * @return 上传结果，包含图片ID
     */
    @Override
    public CommonResult<?> uploadImage(MultipartFile multipart) {
        String newFileName = getNewFileNameOss(multipart);
        String target = getTarget(newFileName,false);
        try {
            String url = aliyunOssUtils.createFile(multipart.getInputStream(), target);
            if (StringUtil.isEmpty(url)) {
                throw new ServiceException(GlobalErrorCodeConstants.IMAGE_UPLOAD_ERROR);
            }
            OssUploadLog ossUploadLog = generationLog(newFileName,target,null);
            ossUploadLogService.save(ossUploadLog);
            return CommonResult.success(Map.of("id", ossUploadLog.getId()));
        } catch (Exception e) {
            e.printStackTrace();
            throw new ServiceException(GlobalErrorCodeConstants.IMAGE_UPLOAD_ERROR);
        }
    }

    /**
     * 上传蒙版图片
     * @param multipart 蒙版图片文件
     * @param originalId 原始图片ID
     * @return 上传结果，包含图片ID
     */
    @Override
    public CommonResult<?> uploadMask(MultipartFile multipart, Integer originalId) {
        String newFileName = getNewFileNameOss(multipart);
        String target = getTarget(newFileName,true);
        try {
            String url = aliyunOssUtils.createFile(multipart.getInputStream(), target);
            if (StringUtil.isEmpty(url)) {
                throw new ServiceException(GlobalErrorCodeConstants.IMAGE_UPLOAD_ERROR);
            }
            OssUploadLog ossUploadLog = generationLog(newFileName,target,originalId);
            ossUploadLogService.save(ossUploadLog);
            return CommonResult.success(Map.of("id", ossUploadLog.getId()));
        } catch (Exception e) {
            e.printStackTrace();
            throw new ServiceException(GlobalErrorCodeConstants.IMAGE_UPLOAD_ERROR);
        }
    }

    /**
     * 获取图片内容地址（回显）
     * @return 图片内容
     */
    @Override
    public CommonResult<?> feedback(Integer id) {
        OssUploadLog ossUploadLog = ossUploadLogService.getById(id);
        if (ossUploadLog == null) {
            throw new ServiceException(GlobalErrorCodeConstants.IMAGE_NOT_FOUND);
        }
        //获取OSS图片网站地址
        String viewUrl = aliyunOssUtils.getUrl(ossUploadLog.getOssPath());
        return CommonResult.success(viewUrl);
    }



    /**
     * 获取文件输入流
     * @param filePath
     * @return
     */
    @Override
    public InputStream getFileInputStream(String filePath) {
        return aliyunOssUtils.getFileInputStream(filePath);
    }

    /**
     * 获取新的文件名（OSS）
     * @param multipart
     * @return
     */
    private String getNewFileNameOss(MultipartFile multipart) {
        String originalFilename = multipart.getOriginalFilename();
        String fileExtension = originalFilename.substring(originalFilename.lastIndexOf("."));
        if (!Arrays.asList(IMAGE_TYPE).contains(fileExtension.toLowerCase())) {
            throw new ServiceException(GlobalErrorCodeConstants.IMAGE_UPLOAD_ERROR);
        }
        String username = SecurityContextHolder.getContext().getAuthentication().getName();
        String randomSuffix = System.currentTimeMillis() + fileExtension;
        return randomSuffix;
    }



    @NotNull
    private static String getTarget(String newFileName,boolean isMask) {
        String username = SecurityUtils.getCurrentUsername();
        if (isMask){
            return USERS_FILE_PAHT+username+"/"+CLIPSPACE+"/"+newFileName;
        }
        return USERS_FILE_PAHT+username+"/"+newFileName;
    }

    /**
     * 生成日志
     * @return
     */
    private OssUploadLog generationLog(String tname,String tpath,Integer originalId) {
        MyUser user = SecurityUtils.getCurrentUser();

        return new OssUploadLog()
                .setUserId(Long.valueOf(user.getId()))
                .setUsername(user.getUsername())
                .setNickname(user.getNickname())
                .setRole(user.getRole())
                .setOssName(tname)
                .setOssPath(tpath)
                .setOriginalId(originalId)
                .setDeleted(0);

    }
}

